﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class admin_ManageMenu : System.Web.UI.Page
{
    public DataSet dsMenu = new DataSet();
    string opcion = null;
    int menu = 2;

    protected void Page_Load(object sender, EventArgs e)
    {
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {
            try
            {
                string rxml = null;
                
                if (Session["MenuType"] != null)
                {
                    string aux = (string)Session["MenuType"];
                    menu = int.Parse(aux);
                    cb_menu.SelectedValue = aux;
                    Session["MenuType"] = null;
                }
                else if(Request.QueryString["id"] != null)
                {
                    opcion = Request.QueryString["id"].ToString();
                    string[] id = opcion.Split('_');
                    if (id != null)
                    {
                        menu = int.Parse(id[0]);
                    }
                }
                    com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                    rxml = service.getMenus(1, menu);

                    if (!rxml.Equals("") || rxml != null)
                    {
                        dsMenu = Utility.getPermitMenu(rxml);
                    }
            }
            catch (Exception ee)
            {
                Utility.writeError(ee.Message);
            }
        }

        if (!Page.IsPostBack)
        {
            //Session["Menu"] = dsMenu;
            //dsMenu = (DataSet)Session["Menu"];
            if (dsMenu != null)
            {
                fillOptions(dsMenu);

                tb_opcion.Text = string.Empty;
                tb_url.Text = string.Empty;
                cb_menu.SelectedValue = menu.ToString();
                if (Request.QueryString["id"] != null)
                {
                    opcion = Request.QueryString["id"].ToString();
                    /*List<TreeNode> lista = Find(opcion);
                    foreach (TreeNode item in lista)
                    {
                        if (tb_opcion.Text.IndexOf(item.Text) == -1)
                        {
                            tb_opcion.Text = item.Text;
                        }
                    }*/
                    string[] id = opcion.Split('_');
                    if (id != null)
                    {
                        if (opcion != "1_0" && opcion != "2_0")
                        {
                            for (int a = 0; a < dsMenu.Tables[int.Parse(id[1])].Rows.Count; a++)
                            {
                                if (dsMenu.Tables[int.Parse(id[1])].Rows[a]["id"].ToString() == id[2])
                                {
                                    tb_opcion.Text = dsMenu.Tables[int.Parse(id[1])].Rows[a]["name"].ToString();
                                    if (dsMenu.Tables[int.Parse(id[1])].Rows[a]["url"].ToString() != "")
                                        tb_url.Text = dsMenu.Tables[int.Parse(id[1])].Rows[a]["url"].ToString();
                                    else
                                        tb_url.Text = "None";
                                    lb_orden.Text = dsMenu.Tables[int.Parse(id[1])].Rows[a]["orden"].ToString();
                                    //l1.Text = "ID=" + dsMenu.Tables[int.Parse(id[1])].Rows[a]["id"].ToString() + " Tabla=" + id[1].ToString() + " Menu=" + menu.ToString();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
      
    }
    
    private List<TreeNode> Find(string param)
    {
        List<TreeNode> list = new List<TreeNode>();
        foreach (TreeNode item in arbol.Nodes)
        {
            if (item.Value.Contains(param))
            {
                list.Add(item);
            }
            if (item.ChildNodes.Count > 0)
            {
                list.AddRange(FindChild(item.ChildNodes, param));
            }
        }
        return list;
    }

    private List<TreeNode> FindChild(TreeNodeCollection nodes, string param)
    {
        List<TreeNode> list = new List<TreeNode>();
        foreach (TreeNode item in nodes)
        {
            if (item.Value.Contains(param))
            {
                list.Add(item);
            }
            if (item.ChildNodes.Count > 0)
            {
                list.AddRange(FindChild(item.ChildNodes, param));
            }
        }
        return list;
    }

    private void fillOptions(DataSet dsMenu)
    {
        TreeNode nodoRaiz = null;
        arbol.Nodes.Clear();
        if (menu == 2)
        {
            nodoRaiz = new TreeNode("&nbsp;&nbsp;MENU INTERNAL");
            nodoRaiz.NavigateUrl = "ManageMenu.aspx?id=2_0";
        }
        else if (menu == 1)
        {
            nodoRaiz = new TreeNode("&nbsp;&nbsp;MENU EXTERNAL");
            nodoRaiz.NavigateUrl = "ManageMenu.aspx?id=1_0";
        }
        
        nodoRaiz.Expand();

        if(dsMenu.Tables.Count >= 1)
            for (int i = 0; i < dsMenu.Tables[0].Rows.Count; i++)
            {
                TreeNode nodoPadre = new TreeNode(dsMenu.Tables[0].Rows[i]["name"].ToString().ToUpper(), menu + "_0_" + dsMenu.Tables[0].Rows[i]["id"].ToString());
                nodoPadre.SelectAction = TreeNodeSelectAction.Expand;
                nodoPadre.Collapse();
                nodoPadre.ImageUrl = "~/img/checkdone.png";
                nodoPadre.NavigateUrl = "ManageMenu.aspx?id=" + menu + "_0_" + dsMenu.Tables[0].Rows[i]["id"].ToString();

                if (dsMenu.Tables.Count >= 2)
                    for (int j = 0; j < dsMenu.Tables[1].Rows.Count; j++)
                    {
                        if (dsMenu.Tables[0].Rows[i]["id"].ToString() == dsMenu.Tables[1].Rows[j]["menu_id"].ToString())
                        {
                            TreeNode nodoHijo1 = new TreeNode(Utility.toCapital(dsMenu.Tables[1].Rows[j]["name"].ToString()), menu + "_1_" + dsMenu.Tables[1].Rows[j]["id"].ToString());
                            nodoHijo1.SelectAction = TreeNodeSelectAction.Expand;
                            nodoHijo1.Collapse();
                            nodoHijo1.NavigateUrl = "ManageMenu.aspx?id=" + menu + "_1_" + dsMenu.Tables[1].Rows[j]["id"].ToString();

                            if (dsMenu.Tables.Count >= 3)
                                for (int a = 0; a < dsMenu.Tables[2].Rows.Count; a++)
                                {
                                    if (dsMenu.Tables[1].Rows[j]["id"].ToString() == dsMenu.Tables[2].Rows[a]["option_id"].ToString())
                                    {
                                        TreeNode nodoHijo2 = new TreeNode(Utility.toCapital(dsMenu.Tables[2].Rows[a]["name"].ToString()), menu + "_2_" + dsMenu.Tables[2].Rows[a]["id"].ToString());
                                        nodoHijo2.SelectAction = TreeNodeSelectAction.Expand;
                                        nodoHijo2.Collapse();
                                        nodoHijo2.NavigateUrl = "ManageMenu.aspx?id=" + menu + "_2_" + dsMenu.Tables[2].Rows[a]["id"].ToString();
                                        nodoHijo1.ChildNodes.Add(nodoHijo2);
                                    }
                                }
                            nodoPadre.ChildNodes.Add(nodoHijo1);
                        }
                    }
                nodoRaiz.ChildNodes.Add(nodoPadre);
            }
        //nodoRaiz.CollapseAll();
        nodoRaiz.ImageUrl = "~/img/ImaPages/Menu.png";
        arbol.Nodes.Add(nodoRaiz);
        arbol.CssClass = "item";
        arbol.Attributes.Add("Style", "font-size:13px; font-family:Arial; padding-left:25px");
        arbol.ShowLines = true;
    }

    private string crearXMLUpdate(string menu, string table, string id, string name, string url)
    {
        string result = "";
        
        result += "<?xml version=\"1.0\" encoding=\"utf-8\"?><data><table>" + table + "</table><menu>" + menu + "</menu>";
        result += "<id>" + id + "</id><name>" + name + "</name><url>" + url + "</url>";
        result += "</data>";

        return result;
    }

    private string crearXMLDelete(string menu, string table, string id, string option)
    {
        string result = "";

        result += "<?xml version=\"1.0\" encoding=\"utf-8\"?><data><table>" + table + "</table><menu>" + menu + "</menu><id>" + id + "</id><option>" + option + "</option>";
        result += "</data>";

        return result;
    }

    private string crearXMLAdd(string menu, string table, string id, string opc, string name, string url, string option)
    {
        string result = "";

        result += "<?xml version=\"1.0\" encoding=\"utf-8\"?><data><table>" + table + "</table><menu>" + menu + "</menu><id>" + id + "</id><option>" + opc + "</option>";
        result += "<name>" + name + "</name><url>" + url + "</url><idoption>" + option + "</idoption>";
        result += "</data>";

        return result;
    }

    protected void chk_new_CheckedChanged(object sender, EventArgs e)
    {
        if (chk_new.Checked == true)
        {
            tb_opcion.Text = string.Empty;
            tb_url.Text = string.Empty;
            lnk_add.Visible = true;
            lnk_cancel.Visible = true;
            lnk_save.Visible = false;
            lnk_delete.Visible = false;
            cb_option.Visible = true;
            lb_option.Visible = true;
            
        }
        else
        {
            lnk_save.Visible = true;
            lnk_delete.Visible = true;
            lnk_add.Visible = false;
            lnk_cancel.Visible = false;
            cb_option.Visible = false;
            lb_option.Visible = false;
        }
    }
    protected void cb_menu_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["MenuType"] = cb_menu.SelectedValue.ToString();
        Response.Redirect("ManageMenu.aspx");
    }

    protected void lnk_save_Click(object sender, EventArgs e)
    {
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        if (chk_new.Checked == false && tb_opcion.Text != "")
        {
            if (Request.QueryString["id"] != null)
            {
                opcion = Request.QueryString["id"].ToString();
                string[] id = opcion.Split('_');
                if (id != null && id.Length > 2)
                {
                    string xml = crearXMLUpdate(cb_menu.SelectedValue, id[1], id[2], tb_opcion.Text, tb_url.Text);
                    int resp = service.updateDataMenu(xml);
                    Response.Redirect("ManageMenu.aspx");
                }
                else
                {
                    Response.Write("<script>alert('Error');</script>");
                }
            }
            else
            {
                Response.Write("<script>alert('Error');</script>");
            }
        }
        else
        {
            Response.Write("<script>alert('Error');</script>");
        }
    }

    protected void lnk_delete_Click(object sender, EventArgs e)
    {
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        if (chk_new.Checked == false && tb_opcion.Text != "")
        {
            if (Request.QueryString["id"] != null)
            {
                int resp = 0;
                opcion = Request.QueryString["id"].ToString();
                string[] id = opcion.Split('_');
                if (id != null && id.Length > 2)
                {
                    for (int a = 0; a < dsMenu.Tables[int.Parse(id[1])].Rows.Count; a++)
                    {
                        if (dsMenu.Tables[int.Parse(id[1])].Rows[a]["id"].ToString() == id[2])
                        {
                            string opc = "";
                            switch (int.Parse(id[1]))
                            {
                                case 0: opc = dsMenu.Tables[int.Parse(id[1])].Rows[a]["option"].ToString(); break;
                                case 1: opc = dsMenu.Tables[int.Parse(id[1])].Rows[a]["option"].ToString(); break;
                            }
                            string xml = crearXMLDelete(cb_menu.SelectedValue, id[1], id[2], opc);
                            resp = service.deleteDataMenu(xml);
                            break;
                        }
                    }
                }
                if (resp == 1)
                    Response.Redirect("ManageMenu.aspx");
            }
            else
            {
                Response.Write("<script>alert('Error');</script>");
            }
        }
        else
        {
            Response.Write("<script>alert('Error');</script>");
        }
    }

    protected void lnk_add_Click(object sender, EventArgs e)
    {
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        if (chk_new.Checked == true && tb_opcion.Text != "")
        {
            if (Request.QueryString["id"] != null)
            {
                int resp = 0;
                opcion = Request.QueryString["id"].ToString();
                string[] id = opcion.Split('_');
                if (id != null)
                {
                    if (id.Length > 2)
                    {
                        for (int a = 0; a < dsMenu.Tables[int.Parse(id[1])].Rows.Count; a++)
                        {
                            if (dsMenu.Tables[int.Parse(id[1])].Rows[a]["id"].ToString() == id[2])
                            {
                                string opc = "";
                                switch (int.Parse(id[1]))
                                {
                                    case 0: opc = dsMenu.Tables[int.Parse(id[1])].Rows[a]["option"].ToString(); break;
                                    case 1: opc = dsMenu.Tables[int.Parse(id[1])].Rows[a]["option"].ToString(); break;
                                }
                                string xml = crearXMLAdd(cb_menu.SelectedValue, id[1], id[2], opc, tb_opcion.Text, tb_url.Text, cb_option.SelectedValue);
                                resp = service.addDataMenu(xml);
                                break;
                            }
                        }
                    }
                    else
                    {
                        string xml = crearXMLAdd(cb_menu.SelectedValue, id[1], "0", "", tb_opcion.Text, tb_url.Text, cb_option.SelectedValue);
                        resp = service.addDataMenu(xml);
                    }
                }
                if (resp == 1)
                    Response.Redirect("ManageMenu.aspx");
            }
            else
            {
                Response.Write("<script>alert('Error');</script>");
            }
        }
        else
        {
            Response.Write("<script>alert('Error');</script>");
        }
    }
    protected void lnk_cancel_Click(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        RE_GenericBean interval;
        if (Request.QueryString["id"] != null)
        {
            opcion = Request.QueryString["id"].ToString();
            string[,] info = new string[,] { { "tbl_menu", "men_id", "men_type" }, { "tbl_menu_opcion", "mopc_id", "mopc_men_id" }, { "tbl_menu_subopcion", "mopc_id", "mopc_mopc_id" } };
            string[] id = opcion.Split('_');
            if (id != null)
            {
                interval = DB.intOrden(info[int.Parse(id[1]), 0], info[int.Parse(id[1]), 1], info[int.Parse(id[1]), 2], int.Parse(id[2]));
                int orden = int.Parse(lb_orden.Text);
                if (orden > interval.intC1)
                {
                    int resp = DB.getOppOrden(info[int.Parse(id[1]), 0], info[int.Parse(id[1]), 1], int.Parse(id[2]), orden, info[int.Parse(id[1]), 2], 0);
                    if (resp == 1)
                    {
                        orden -= 1;
                        lb_orden.Text = orden.ToString();
                        if (orden == interval.intC1) Button1.Enabled = false; else if (orden > interval.intC1) Button1.Enabled = true;
                        if (orden == interval.intC2) Button2.Enabled = false; else if (orden < interval.intC2) Button2.Enabled = true;
                        Response.Redirect("ManageMenu.aspx?id=" + opcion);
                    }
                }
                
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        RE_GenericBean interval;
        if (Request.QueryString["id"] != null)
        {
            opcion = Request.QueryString["id"].ToString();
            string[,] info = new string[,] { { "tbl_menu", "men_id", "men_type" }, { "tbl_menu_opcion", "mopc_id", "mopc_men_id" }, { "tbl_menu_subopcion", "mopc_id", "mopc_mopc_id" } };
            string[] id = opcion.Split('_');
            if (id != null)
            {
                interval = DB.intOrden(info[int.Parse(id[1]), 0], info[int.Parse(id[1]), 1], info[int.Parse(id[1]), 2], int.Parse(id[2]));
                int orden = int.Parse(lb_orden.Text);
                if (orden < interval.intC2)
                {
                    int resp = DB.getOppOrden(info[int.Parse(id[1]), 0], info[int.Parse(id[1]), 1], int.Parse(id[2]), orden, info[int.Parse(id[1]), 2], 1);
                    if (resp == 1)
                    {
                        orden += 1;
                        lb_orden.Text = orden.ToString();
                        if (orden == interval.intC1) Button1.Enabled = false; else if (orden > interval.intC1) Button1.Enabled = true;
                        if (orden == interval.intC2) Button2.Enabled = false; else if (orden < interval.intC2) Button2.Enabled = true;
                        Response.Redirect("ManageMenu.aspx?id=" + opcion);
                    }
                }
                
            }
        }
    }
}